package com.zd.commodity.productMng.dao.impl;

import java.sql.Timestamp;

import javax.annotation.Resource;

import org.apache.struts2.ServletActionContext;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.zd.commodity.dao.impl.BaseDao;
import com.zd.commodity.productMng.dao.IProductSeriesDao;
import com.zd.commodity.productMng.entity.ProductSeries;
import com.zd.commodity.userMng.entity.User;

@Repository("productSeriesDao")
public class ProductSeriesDaoImpl extends BaseDao<ProductSeries> implements IProductSeriesDao {

	@Resource(name = "sessionFactory")
	public void setSuperSessionFactory(SessionFactory sessionFactory){
		super.setSessionFactory(sessionFactory);
	}
	
	@Override
	public DetachedCriteria getDetachedCriteria(ProductSeries t1,ProductSeries t2,Object params){
		DetachedCriteria dc=DetachedCriteria.forClass(ProductSeries.class);
		if(t1!=null){
			if(t1.getName()!=null && !t1.getName().equals("")){
				dc.add(Restrictions.like("name", t1.getName(), MatchMode.ANYWHERE));
			}
			if(t1.getCategory()!=null){
				dc.createAlias("category", "c");
				if(t1.getCategory().getName()!=null && !t1.getCategory().getName().equals("")){
					dc.add(Restrictions.like("c.name", t1.getCategory().getName(), MatchMode.ANYWHERE));
				}
				if(t1.getCategory().getId()!=null && !t1.getCategory().getId().equals("")){
					dc.add(Restrictions.eq("c.id", t1.getCategory().getId()));
				}
			}
			if(t1.getBrandShow()!=null){
				dc.createAlias("brandShow", "b");
				if(t1.getBrandShow().getName()!=null && !t1.getBrandShow().getName().equals("")){
					dc.add(Restrictions.like("b.name", t1.getBrandShow().getName(), MatchMode.ANYWHERE));
				}
			}
		}
		dc.addOrder(Order.desc("creationTime"));
		return dc;
	}
	
	@Override
	public void add(ProductSeries t){
		User user=(User)ServletActionContext.getRequest().getSession().getAttribute("user");
	    
		Timestamp time=new Timestamp(System.currentTimeMillis());
		
		t.setCreationTime(time);
		t.setCreator(user.getUsername());
		getHibernateTemplate().save(t);
	}
	
	@Override
	public void update(ProductSeries t){
		User user=(User)ServletActionContext.getRequest().getSession().getAttribute("user");
	    
		Timestamp time=new Timestamp(System.currentTimeMillis());
		
		t.setUpdateTime(time);
		t.setUpdater(user.getUsername());
		getHibernateTemplate().update(t);
	}
}
